package com.ruoyi.quartz.util;

import com.ruoyi.common.annotation.TaskClass;
import com.ruoyi.common.annotation.TaskMethod;
import com.ruoyi.quartz.domain.JobMethod;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
 * 定时任务可选类可选方法及方法参数列表
 * @author wenbei
 * @Date 2021-1-9
 */
@Component
public class JobOptionalUtil implements ApplicationContextAware {
    private ApplicationContext context;
    private static ConcurrentHashMap<String, List<JobMethod>> taskBeanMethods = new ConcurrentHashMap<>();
    private static List<String> classNames = Lists.newArrayList();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    @PostConstruct
    public void getAllTaskClass(){
        Map<String, Object> taskClasses = context.getBeansWithAnnotation(TaskClass.class);
        taskBeanMethods.clear();
        taskClasses.forEach((k,v)-> {
            Method[] methods = v.getClass().getMethods();
            List<JobMethod> methodsName = Arrays.stream(methods)
                    .filter(m->m.isAnnotationPresent(TaskMethod.class))
                    .map(m -> {
                        JobMethod jobMethod = new JobMethod();
                        jobMethod.setMethodName(m.getName());
                        Class[] paramTypes = m.getParameterTypes();
                        List<String> collect = Arrays.stream(paramTypes)
                                .map(p -> p.getName())
                                .collect(Collectors.toList());
                        jobMethod.setParamTypes(collect);
                        return jobMethod;
                    })
                    .collect(Collectors.toList());
            taskBeanMethods.put(k,methodsName);
            classNames.add(k);
        });
    }
    public static List<String> getAllTaskClassName(){
        return classNames;
    }
    public static List<JobMethod> getClassMethodsByClassName(String className){
        return taskBeanMethods.get(className);
    }
}
